<?php
/**
 * Created by PhpStorm.
 * User: leo
 * Date: 16/4/6
 * Time: 下午5:36
 * Describe:
 */

namespace services\sms;


class JianZSms extends SmsBase
{

    public $account;
    public $password;
    public $accountYx;
    private $client;
    private $err_msg;
    protected $url = 'http://www.jianzhou.sh.cn/JianzhouSMSWSServer/services/BusinessService';

    private $result;
    private $signature = '【有试吗】';
    private $ext = '退订回TD';

    /**
     * @param string $cell
     * @param string $content
     * @param string $sendTime
     * @return array
     *
     *
     */
    protected function getDataStruct($cell = '', $content = '', $sendTime = '')
    {
        $data = array(

            'account' => $this->account,
            'password' => $this->password,


        );
        if ($this->marketing) {
            $data['account'] = $this->accountYx;
        }
        return $data;

    }



    public function __construct()
    {
        $this->signature = '【有试吗】';
        $this->client = new \nusoap_client($this->url . '?wsdl', true);
        $this->client->soap_defencoding = 'utf-8';
        $this->client->decode_utf8 = false;
        $this->client->xml_encoding = 'utf-8';

        $err = $this->client->getError();
        if ($err) {
            $this->err_msg = $err;
        }

        parent::__construct();


    }

    private function postData($func, $params)
    {
        /*
         * 测试机
         */
        /*if ($_SERVER['SERVER_ADDR'] == '172.16.3.210')
            return array('sendBatchMessageReturn' => rand(100000, 900000),
                'sendPersonalMessagesReturn' => rand(100000, 900000),

            );*/


        $this->result = '';
        $this->result = $this->client->call($func, $params, $this->url);
        $this->err_msg = $this->client->getError();

        if ($this->client->fault) {
            return false;
        } else {
            return true;
        }

    }


    public function setSingleMsm($cell, $content, $uid = 0, $department = 12, $sendTime = '')
    {

        $method = 'sendBatchMessage';
        // 修正手机号码格式
        $cell = trim($cell);

        // 检查频度
        $check_flag = $this->cellCheck($cell, $content);

        if ($check_flag == true) {
            $this->saveErrorMsg($method, $content, '频繁发送', $cell);
            return false;
        }
        $params = $this->getDataStruct();
        $params['destmobile'] = $cell;
        $params['msgText'] = $content . $this->signature;
        if ($sendTime) {
            /**
             * 日期格式: yyyymmddhhmmss
             */
            $params['sendDateTime'] = preg_replace('/[:\s-]/', '', $sendTime);
            $method = 'sendTimelyMessage';

        }


        $flag = $this->postData($method, $params);

        if ($flag && !$this->err_msg) {
            $taskId = $sendTime ? $this->result['sendTimelyMessageReturn'] : $this->result['sendBatchMessageReturn'];
            $this->saveData($taskId, $cell, $content, $uid, $department, $sendTime);
            return true;
        }

        $this->saveErrorMsg($method, $params, $this->err_msg, $cell);
        return false;


    }


    /**
     * @param array $cell 目标手机号，多个手机号码用||分割;
     * @param array $content 短消息内容,多个内容用||分隔;
     * @param int $uid
     * @param int $department
     * @param string $sendTime
     * @return array
     * 批量发送个性化短信
     * 建周短信, 需要自己加后缀.
     * 号码和内容||分隔数量必须相等
     * 相同内容禁止使用此方法，
     * 请使用sendBatchMessage方法
     *
     *
     */
    public function sendPersonalMessages($cell, $content, $uid = 0, $department = 12, $sendTime = '')
    {
        if (is_array($cell) && is_array($content)) {
            if (count($cell) != count($content)) {
                $this->saveErrorMsg('sendPersonalMessages', implode('||', $cell) . implode('||', $content), '手机号码内容数量不对称');
                return false;
            }

            $newSignature = $this->signature;
            if ($this->marketing) {
                $newSignature = $this->ext . $newSignature;
            }

            $contentNew = implode('||', array_map(function ($item, $signature) {
                return $item . $signature;
            }, $content, array_fill(0, count($content), $newSignature)));

            $cellNew = implode('||', $cell);
        } else {
            $this->saveErrorMsg('sendPersonalMessages', serialize($cell) . serialize($content), '参数类型不正确');
            return false;
        }


        $params = $this->getDataStruct();
        $params['destMobiles'] = $cellNew;
        $params['msgContents'] = $contentNew;


        $flag = $this->postData('sendPersonalMessages', $params);
        /*
         * 提交成功，数据写入sms_new, 否则写入sms_new_pre等待下次提交
         */
        if ($flag && !$this->err_msg) {
            for ($i = 0; $i < count($cell); $i++) {
                $this->saveData($this->result ['sendPersonalMessagesReturn'], $cell[$i], $content[$i], $uid, $department, $sendTime);
            }
            return false;

        } else {

            $this->saveErrorMsg('sendPersonalMessages', $cellNew . '_||_' . $contentNew, $this->err_msg, '');
            for ($i = 0; $i < count($cell); $i++) {
                $this->sms->savePre($cell[$i], $content[$i], 0, $department);
            }
        }

        return true;
    }

    /**
     * @param array $cell
     * @param string $content
     * @param int $uid
     * @param int $department
     * @param string $sendTime
     * @return bool
     *
     * 群发短信，
     * 适合不同手机号，　
     * 相同内容群发，　
     * 多个手机号用；分隔
     */
    public function sendBatchMessage($cell, $content, $uid = 0, $department = 12, $sendTime = '')
    {

        $cellNew = '';
        if (is_array($cell)) {
            $cellNew = implode(';', $cell);
        }
        $params = $this->getDataStruct();
        $params['destmobile'] = $cellNew;
        $newSignature = $this->signature;
        if ($this->marketing) {
            $newSignature = $this->ext . $newSignature;
        }

        $params['msgText'] = $content . $newSignature;

        $flag = $this->postData('sendBatchMessage', $params);

        if ($flag && !$this->err_msg) {
            foreach ($cell as $c) {

                $this->saveData($this->result ['sendBatchMessageReturn'], $c, $content, $uid, $department, $sendTime);
            }
            return true;
        } else {

            foreach (explode(';', $cell) as $c) {
                $this->sms->savePre($c, $content, 0, $department);
            }
            $this->saveErrorMsg('sendBatchMessage', $params, $this->err_msg, '');
            return false;
        }

    }

    /**
     * @return array
     *
     * 取回用户回复信息
     * 处理成数组后返回
     * 多条短信用　｜分隔，　
     * 每条短信用，分隔，　依次：手机号，　内容，　时间
     * 内容为ｕｎｉｃｏｄｅ码
     */
    public function getReceivedMsg()
    {
        $flag = $this->postData('getReceivedMsg', array(
            'param' => 0
        ));
        if ($flag && !$this->err_msg) {
            $this->saveErrorMsg('getReceivedMsgReturn', '取上行数据', $this->err_msg, '');
            return false;
        } else {
            foreach (explode('|', $this->result['getReceivedMsgReturn']) as $line) {
                if (!$line) break;
                $line = explode(',', $line);
                $content = static::unicode_decode($line[1]);
                $this->saveReceived(0, $line[0], $content, $line[2]);

            }
            return true;
        }


    }

    /**
     * @return int|bool
     *
     * 接收用户信息(包括余额等)
     *
     */
    public function getUserInfo()
    {
        $this->postData('getUserInfo', $this->getDataStruct());
        if (!$dom = simplexml_load_string($this->result['getUserInfoReturn'])) {
            return false;
        }
        $result = json_decode(json_encode($dom), true);

        return (int)$result['remainFee'];

    }

    /**
     * @param string $context 接口返回数据
     * @return mixed
     * webservice 用不到此方法
     */
    public function parseResult($context)
    {

        return $context;
    }

    /**
     * 建周主动推送状态, 无获取状态方法
     */
    public function getSmsStatus()
    {
    }

    function replace_unicode_escape_sequence($match)
    {
        return mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UCS-2BE');
    }

    public static function unicode_decode($str)
    {
        return preg_replace_callback('/\\\\u([0-9a-f]{4})/i', 'replace_unicode_escape_sequence', $str);
    }


}